{% extends theme_path('admin/base.html') %}

{% block title %}分类管理{% endblock %}

{% block content %}
<div class="p-6">
    <div class="bg-white rounded-lg shadow-sm">
        <div class="px-6 py-4 border-b">
            <div class="flex flex-col lg:flex-row justify-between items-stretch lg:items-center space-y-4 lg:space-y-0">
                <h2 class="text-xl font-bold">分类管理</h2>
                <div class="flex flex-col sm:flex-row items-stretch sm:items-center space-y-4 sm:space-y-0 sm:space-x-4 w-full lg:w-auto">
                    <form method="get" class="flex flex-col sm:flex-row items-stretch sm:items-center space-y-4 sm:space-y-0 sm:space-x-4 flex-1">
                        <select name="search_type" 
                               class="w-full sm:w-auto px-3 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-blue-500">
                            <option value="name" {% if search_type != 'id' %}selected{% endif %}>名称</option>
                            <option value="id" {% if search_type == 'id' %}selected{% endif %}>ID</option>
                        </select>
                        <div class="relative flex-1">
                            <input type="text" name="q" value="{{ search_query }}"
                                   placeholder="搜索分类..." 
                                   class="w-full pl-10 pr-4 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-blue-500">
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                <svg class="h-5 w-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
                                </svg>
                            </div>
                        </div>
                        <button type="submit" 
                                class="w-full sm:w-auto px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
                            搜索
                        </button>
                    </form>
                    <div class="flex flex-col sm:flex-row gap-2">
                        <button onclick="updateAllCategoryCounts()" 
                                class="w-full sm:w-auto px-4 py-2 bg-emerald-500 text-white rounded-lg hover:bg-emerald-600 text-sm sm:text-base">
                            <span class="flex items-center justify-center">
                                <svg class="w-5 h-5 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 
                                          d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15">
                                    </path>
                                </svg>
                                <span class="hidden sm:inline">更新所有计数</span>
                                <span class="sm:hidden">更新计数</span>
                            </span>
                        </button>
                        <button onclick="showAddCategoryModal()" 
                                class="w-full sm:w-auto px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 text-sm sm:text-base">
                            <span class="flex items-center justify-center">
                                <svg class="w-5 h-5 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
                                </svg>
                                <span class="hidden sm:inline">添加分类</span>
                                <span class="sm:hidden">添加分类</span>
                            </span>
                        </button>
                        <button onclick="showBatchPerPageModal()" 
                                class="w-full sm:w-auto px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 text-sm sm:text-base">
                            <span class="flex items-center justify-center">
                                <svg class="w-5 h-5 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16m-7 6h7"></path>
                                </svg>
                                <span class="hidden sm:inline">批量设置</span>
                                <span class="sm:hidden">批量设置</span>
                            </span>
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <div class="overflow-x-auto">
            <!-- 桌面端表格 -->
            <table class="hidden sm:table min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-4 sm:px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
                        <th class="px-4 sm:px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">名称</th>
                        <th class="hidden sm:table-cell px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">别名</th>
                        <th class="hidden sm:table-cell px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">描述</th>
                        <th class="hidden sm:table-cell px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">文章数</th>
                        <th class="hidden sm:table-cell px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">每页数量</th>
                        <th class="hidden sm:table-cell px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">访问方式</th>
                        <th class="hidden sm:table-cell px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">模板</th>
                        <th class="px-4 sm:px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200" id="categoryList">
                    {% for category in pagination.items recursive %}
                    <tr data-id="{{ category.id }}" data-category-id="{{ category.id }}" {% if category.parent_id %}data-parent="{{ category.parent_id }}"{% endif %} class="category-item">
                        <td class="px-4 sm:px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ category.id }}</td>
                        <td class="px-4 sm:px-6 py-4">
                            <div class="flex items-center">
                                <!-- 缩进 -->
                                <div class="w-{{ category.get_level() * 8 }}"></div>
                                <!-- 展开/折叠按钮 -->
                                {% if category.children.count() > 0 %}
                                <button class="toggle-children mr-2" onclick="toggleChildren({{ category.id }}, this)">
                                    <svg class="w-4 h-4 transform transition-transform duration-200" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
                                    </svg>
                                </button>
                                {% else %}
                                <div class="w-6 mr-2"></div>
                                {% endif %}
                                <span class="font-medium text-gray-900"><a target="_blank" href="{{ url_for('blog.category', id=category.slug if category.use_slug else category.id) }}" >{{ category.name }}</a></span>
                            </div>
                            <!-- 移动端显示的额外信息 -->
                            <div class="sm:hidden mt-2 text-xs space-y-2 bg-gray-50 dark:bg-gray-700/50 p-3 rounded-lg">
                                <div class="grid grid-cols-2 gap-2">
                                    <div class="flex items-center">
                                        <span class="text-gray-500 dark:text-gray-400 mr-1">别名:</span>
                                        <span class="text-gray-900 dark:text-gray-300">{{ category.slug }}</span>
                                    </div>
                                    <div class="flex items-center">
                                        <span class="text-gray-500 dark:text-gray-400 mr-1">文章数:</span>
                                        <span class="text-gray-900 dark:text-gray-300">{{ category.article_count }}</span>
                                    </div>
                                    <div class="flex items-center">
                                        <span class="text-gray-500 dark:text-gray-400 mr-1">每页数量:</span>
                                        <span class="text-gray-900 dark:text-gray-300">{{ category.per_page or '默认(10)' }}</span>
                                    </div>
                                    <div class="flex items-center">
                                        <span class="text-gray-500 dark:text-gray-400 mr-1">模板:</span>
                                        <span class="text-gray-900 dark:text-gray-300">{{ category.template or '默认' }}</span>
                                    </div>
                                </div>
                                <div class="flex items-center">
                                    <span class="text-gray-500 dark:text-gray-400 mr-1">描述:</span>
                                    <span class="text-gray-900 dark:text-gray-300">{{ category.description or '无' }}</span>
                                </div>
                                <div class="flex items-center">
                                    <span class="text-gray-500 dark:text-gray-400 mr-1">访问方式:</span>
                                    {% if category.use_slug %}
                                    <span class="px-2 py-0.5 text-xs bg-emerald-100 text-emerald-800 dark:bg-emerald-900/50 dark:text-emerald-300 rounded">使用别名</span>
                                    {% else %}
                                    <span class="px-2 py-0.5 text-xs bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-300 rounded">使用 ID</span>
                                    {% endif %}
                                </div>
                            </div>
                        </td>
                        <td class="hidden sm:table-cell px-6 py-4 text-sm text-gray-500">{{ category.slug }}</td>
                        <td class="hidden sm:table-cell px-6 py-4 text-sm text-gray-500">{{ category.description or '无' }}</td>
                        <td class="hidden sm:table-cell px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            <span class="article-count">{{ category.article_count }}</span>
                        </td>
                        <td class="hidden sm:table-cell px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ category.per_page or '默认(10)' }}</td>
                        <td class="hidden sm:table-cell px-6 py-4 whitespace-nowrap text-sm">
                            {% if category.use_slug %}
                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                使用别名
                            </span>
                            {% else %}
                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
                                使用 ID
                            </span>
                            {% endif %}
                        </td>
                        <td class="hidden sm:table-cell px-6 py-4 text-sm text-gray-500">{{ category.template or '默认' }}</td>
                        <td class="px-4 sm:px-6 py-4 whitespace-nowrap text-sm">
                            <div class="flex flex-wrap gap-2 mt-2">
                                <button onclick="showAddChildModal({{ category.id }})" 
                                        class="text-emerald-600 dark:text-emerald-400 hover:text-emerald-800 dark:hover:text-emerald-300">
                                    <span class="flex items-center">
                                        <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
                                        </svg>
                                        添加子分类
                                    </span>
                                </button>
                                <button onclick="showEditCategoryModal({{ category.id }})" 
                                        class="text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300">
                                    <span class="flex items-center">
                                        <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
                                        </svg>
                                        编辑
                                    </span>
                                </button>
                                <button onclick="showMoveCategoryModal({{ category.id }})" 
                                        class="text-indigo-600 dark:text-indigo-400 hover:text-indigo-800 dark:hover:text-indigo-300">
                                    <span class="flex items-center">
                                        <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4"></path>
                                        </svg>
                                        移动
                                    </span>
                                </button>
                                <button onclick="deleteCategory({{ category.id }})" 
                                        class="text-rose-600 dark:text-rose-400 hover:text-rose-800 dark:hover:text-rose-300">
                                    <span class="flex items-center">
                                        <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                                        </svg>
                                        删除
                                    </span>
                                </button>
                            </div>
                        </td>
                    </tr>
                    {% if category.children %}
                        {{ loop(category.children)|safe }}
                    {% endif %}
                    {% endfor %}
                </tbody>
            </table>

            <!-- 移动端列表视图 -->
            <div class="sm:hidden divide-y divide-gray-200">
                {% for category in pagination.items recursive %}
                <div class="p-4 space-y-4" data-id="{{ category.id }}" data-category-id="{{ category.id }}" {% if category.parent_id %}data-parent="{{ category.parent_id }}"{% endif %}>
                    <!-- 标题和展开按钮行 -->
                    <div class="flex items-center">
                        <div class="w-{{ category.get_level() * 4 }}"></div>
                        {% if category.children.count() > 0 %}
                        <button class="toggle-children mr-2 p-1" onclick="toggleChildren({{ category.id }}, this)">
                            <svg class="w-4 h-4 transform transition-transform duration-200" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
                            </svg>
                        </button>
                        {% else %}
                        <div class="w-6 mr-2"></div>
                        {% endif %}
                        <span class="text-lg font-medium text-gray-900 dark:text-white"><a target="_blank" href="{{ url_for('blog.category', id=category.slug if category.use_slug else category.id) }}" >{{ category.name }}</a></span>
                    </div>

                    <!-- 分类信息卡片 -->
                    <div class="bg-gray-50 dark:bg-gray-800 rounded-lg p-4 space-y-3">
                        <!-- 基本信息网格 -->
                        <div class="grid grid-cols-2 gap-3">
                            <div>
                                <span class="text-xs text-gray-500 dark:text-gray-400">ID</span>
                                <div class="text-sm text-gray-900 dark:text-gray-300">{{ category.id }}</div>
                            </div>
                            <div>
                                <span class="text-xs text-gray-500 dark:text-gray-400">文章数</span>
                                <div class="text-sm text-gray-900 dark:text-gray-300">
                                    <span class="article-count">{{ category.article_count }}</span>
                                </div>
                            </div>
                            <div>
                                <span class="text-xs text-gray-500 dark:text-gray-400">每页数量</span>
                                <div class="text-sm text-gray-900 dark:text-gray-300">{{ category.per_page or '默认(10)' }}</div>
                            </div>
                            <div>
                                <span class="text-xs text-gray-500 dark:text-gray-400">访问方式</span>
                                <div>
                                    {% if category.use_slug %}
                                    <span class="inline-block px-2 py-0.5 text-xs bg-emerald-100 text-emerald-800 dark:bg-emerald-900/50 dark:text-emerald-300 rounded">使用别名</span>
                                    {% else %}
                                    <span class="inline-block px-2 py-0.5 text-xs bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-300 rounded">使用 ID</span>
                                    {% endif %}
                                </div>
                            </div>
                        </div>

                        <!-- 别名和描述 -->
                        <div class="space-y-2">
                            <div>
                                <span class="text-xs text-gray-500 dark:text-gray-400">别名</span>
                                <div class="text-sm text-gray-900 dark:text-gray-300">{{ category.slug }}</div>
                            </div>
                            <div>
                                <span class="text-xs text-gray-500 dark:text-gray-400">描述</span>
                                <div class="text-sm text-gray-900 dark:text-gray-300">{{ category.description or '无' }}</div>
                            </div>
                            <div>
                                <span class="text-xs text-gray-500 dark:text-gray-400">模板</span>
                                <div class="text-sm text-gray-900 dark:text-gray-300">{{ category.template or '默认' }}</div>
                            </div>
                        </div>

                        <!-- 操作按钮组 -->
                        <div class="flex flex-wrap gap-3 pt-2 border-t border-gray-200 dark:border-gray-700">
                            <button onclick="showAddChildModal({{ category.id }})" 
                                    class="flex items-center text-emerald-600 dark:text-emerald-400">
                                <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
                                </svg>
                                <span>添加子分类</span>
                            </button>
                            <button onclick="showEditCategoryModal({{ category.id }})" 
                                    class="flex items-center text-blue-600 dark:text-blue-400">
                                <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
                                </svg>
                                <span>编辑</span>
                            </button>
                            <button onclick="showMoveCategoryModal({{ category.id }})" 
                                    class="flex items-center text-indigo-600 dark:text-indigo-400">
                                <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4"></path>
                                </svg>
                                <span>移动</span>
                            </button>
                            <button onclick="deleteCategory({{ category.id }})" 
                                    class="flex items-center text-rose-600 dark:text-rose-400">
                                <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                                </svg>
                                <span>删除</span>
                            </button>
                        </div>
                    </div>
                </div>
                {% if category.children %}
                    {{ loop(category.children)|safe }}
                {% endif %}
                {% endfor %}
            </div>
        </div>

        {% if pagination.pages > 1 %}
        <div class="px-6 py-4 mt-4 border-t">
            {% with endpoint='admin.categories', kwargs={'q': search_query, 'search_type': search_type} %}
            {% include 'components/pagination.html' %}
            {% endwith %}
        </div>
        {% endif %}
    </div>
</div>

<!-- 添加/编辑分类的模态框 -->
<div id="categoryModal" class="fixed inset-0 bg-black bg-opacity-50 hidden items-center justify-center z-50">
    <div class="bg-white rounded-lg shadow-xl w-full max-w-md mx-4">
        <div class="px-6 py-4 border-b">
            <h3 class="text-lg font-medium" id="modalTitle">添加分类</h3>
        </div>
        <form id="categoryForm" class="p-6 space-y-4 max-h-[calc(100vh-250px)] overflow-y-auto custom-scrollbar">
            <input type="hidden" name="parent_id" id="parentId">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">名称</label>
                <input type="text" name="name" required
                       class="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">别名</label>
                <input type="text" name="slug"
                       class="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                       placeholder="留空将自动生成">
                <p class="mt-1 text-xs text-gray-500">用于URL的别名，只能包含字母、数字和连字符</p>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">描述</label>
                <textarea name="description" rows="3"
                          class="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"></textarea>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">排序</label>
                <input type="number" name="sort_order" value="0"
                       class="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">访问方式</label>
                <div class="flex items-center">
                    <label class="inline-flex items-center">
                        <input type="checkbox" name="use_slug" class="form-checkbox"
                               {% if category and category.use_slug %}checked{% endif %}>
                        <span class="ml-2">使用别名(slug)访问</span>
                    </label>
                </div>
                <p class="mt-1 text-xs text-gray-500">启用后只能通过别名访问，禁用后只能通过 ID 访问</p>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">分类模板</label>
                <select name="template" 
                        class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:border-blue-500 focus:ring-0">
                    <option value="">使用默认模板</option>
                    {% for template in available_templates %}
                    <option value="{{ template }}" {% if category and category.template == template %}selected{% endif %}>
                        {{ template }}
                    </option>
                    {% endfor %}
                </select>
                <p class="mt-1 text-xs text-gray-500">可以为分类选择特定的模板，留空则使用默认模板</p>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">每页文章数</label>
                <input type="number" name="per_page" 
                       value="{{ category.per_page if category else '' }}"
                       placeholder="留空则使用默认值(10)"
                       min="1" max="100"
                       class="w-full px-3 py-2 border border-gray-300 rounded-md focus:border-blue-500 focus:ring-0">
                <p class="mt-1 text-xs text-gray-500">设置此分类下每页显示的文章数量,建议设置在1-100之间</p>
            </div>
        </form>
        <div class="px-6 py-4 border-t bg-gray-50 flex justify-end space-x-3">
            <button onclick="hideCategoryModal()"
                    class="px-4 py-2 text-gray-700 hover:bg-gray-100 rounded-lg transition-colors duration-200">
                取消
            </button>
            <button onclick="saveCategory()"
                    class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors duration-200">
                保存
            </button>
        </div>
    </div>
</div>

<!-- 移动分类的模态框 -->
<div id="moveCategoryModal" class="fixed inset-0 bg-black bg-opacity-50 hidden items-center justify-center z-50">
    <div class="bg-white rounded-lg shadow-xl w-full max-w-md mx-4">
        <div class="px-6 py-4 border-b">
            <h3 class="text-lg font-medium">移动分类</h3>
        </div>
        <form id="moveCategoryForm" class="p-6 space-y-4">
            <input type="hidden" name="category_id">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">选择新的父分类</label>
                <select name="new_parent_id" 
                        class="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">作为顶级分类</option>
                </select>
            </div>
        </form>
        <div class="px-6 py-4 border-t bg-gray-50 flex justify-end space-x-3">
            <button onclick="hideMoveModal()"
                    class="px-4 py-2 text-gray-700 hover:bg-gray-100 rounded-lg transition-colors duration-200">
                取消
            </button>
            <button onclick="moveCategory()"
                    class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors duration-200">
                移动
            </button>
        </div>
    </div>
</div>

<!-- 批量设置分页的模态框 -->
<div id="batchPerPageModal" class="fixed inset-0 bg-black bg-opacity-50 hidden items-center justify-center z-50">
    <div class="bg-white rounded-lg shadow-xl w-full max-w-md mx-4">
        <div class="px-6 py-4 border-b">
            <h3 class="text-lg font-medium">批量设置每页文章数</h3>
        </div>
        <form id="batchPerPageForm" class="p-6 space-y-4">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">每页文章数</label>
                <input type="number" name="per_page" required
                       min="1" max="100"
                       placeholder="设置所有分类的每页文章数(1-100)"
                       class="w-full px-3 py-2 border border-gray-300 rounded-md focus:border-blue-500 focus:ring-0">
                <p class="mt-1 text-xs text-gray-500">此操作将统一设置所有分类的每页文章数</p>
            </div>
        </form>
        <div class="px-6 py-4 border-t bg-gray-50 flex justify-end space-x-3">
            <button onclick="hideBatchPerPageModal()"
                    class="px-4 py-2 text-gray-700 hover:bg-gray-100 rounded-lg transition-colors duration-200">
                取消
            </button>
            <button onclick="saveBatchPerPage()"
                    class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors duration-200">
                确定设置
            </button>
        </div>
    </div>
</div>
<script src="{{ url_for('static', filename='default/js/Sortable.min.js') }}"></script>
<script>
// 展开/折叠子分类
function toggleChildren(categoryId, button) {
    const icon = button.querySelector('svg');
    icon.classList.toggle('rotate-180');
    
    const rows = document.querySelectorAll(`[data-parent="${categoryId}"]`);
    rows.forEach(row => {
        row.classList.toggle('hidden');
        // 如果当前行被隐藏，同时隐藏其所有子行
        if (row.classList.contains('hidden')) {
            const childRows = document.querySelectorAll(`[data-parent="${row.dataset.id}"]`);
            childRows.forEach(childRow => {
                childRow.classList.add('hidden');
                const childButton = childRow.querySelector('.toggle-children svg');
                if (childButton) {
                    childButton.classList.remove('rotate-180');
                }
            });
        }
    });
}

// 页面加载时初始化分类显示状态
document.addEventListener('DOMContentLoaded', function() {
    // 默认展开所有分类
    document.querySelectorAll('.toggle-children').forEach(button => {
        // 旋转箭头
        const icon = button.querySelector('svg');
        icon.classList.add('rotate-180');
    });
    
    // 显示所有子分类
    document.querySelectorAll('[data-parent]').forEach(row => {
        row.classList.remove('hidden');
    });
});

// 显示添加分类模态框
function showAddCategoryModal(parentId = null) {
    const form = document.getElementById('categoryForm');
    form.reset();
    form.parentId.value = parentId;
    
    document.getElementById('modalTitle').textContent = parentId ? '添加子分类' : '添加分类';
    document.getElementById('categoryModal').classList.remove('hidden');
    document.getElementById('categoryModal').classList.add('flex');
}

// 显示添加子分类模态框
function showAddChildModal(parentId) {
    showAddCategoryModal(parentId);
}

// 隐藏分类模态框
function hideCategoryModal() {
    document.getElementById('categoryModal').classList.add('hidden');
    document.getElementById('categoryModal').classList.remove('flex');
}

// 保存分类
function saveCategory() {
    const form = document.getElementById('categoryForm');
    const formData = new FormData(form);
    const isEdit = form.dataset.editing === 'true';
    
    const url = isEdit 
        ? `{{ admin_url }}/categories/${form.dataset.categoryId}/edit`
        : '{{ admin_url }}/categories/add';
        
    fetch(url, {
        method: 'POST',
        headers: {
            'X-CSRFToken': '{{ csrf_token() }}'
        },
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            showAlert(data.error, 'error', '错误');
        } else {
            showAlert(data.message || '操作成功', 'success', '成功');
            setTimeout(() => location.reload(), 500);
        }
    });
}

// 显示编辑分类模态框
function showEditCategoryModal(categoryId) {
    fetch(`{{ admin_url }}/categories/${categoryId}`)
        .then(response => response.json())
        .then(category => {
            const form = document.getElementById('categoryForm');
            form.dataset.editing = 'true';
            form.dataset.categoryId = categoryId;
            form.name.value = category.name;
            form.slug.value = category.slug;
            form.description.value = category.description || '';
            form.sort_order.value = category.sort_order;
            form.parentId.value = category.parent_id || '';
            form.querySelector('[name="use_slug"]').checked = category.use_slug;
            form.querySelector('[name="template"]').value = category.template || '';
            form.per_page.value = category.per_page || '';
            document.getElementById('modalTitle').textContent = '编辑分类';
            document.getElementById('categoryModal').classList.remove('hidden');
            document.getElementById('categoryModal').classList.add('flex');
        });
}

// 显示移动分类模态框
function showMoveCategoryModal(categoryId) {
    const form = document.getElementById('moveCategoryForm');
    form.category_id.value = categoryId;
    
    // 获取所有分类
    fetch('{{ admin_url }}/categories/all')
        .then(response => response.json())
        .then(categories => {
            const select = form.new_parent_id;
            select.innerHTML = '<option value="">作为顶级分类</option>';
            
            function addOptions(categories, level = 0) {
                categories.forEach(category => {
                    // 不能移动到自己的子分类下
                    if (category.id != categoryId) {
                        const option = document.createElement('option');
                        option.value = category.id;
                        option.textContent = '　'.repeat(level) + category.name;
                        select.appendChild(option);
                        
                        if (category._children) {
                            addOptions(category._children, level + 1);
                        }
                    }
                });
            }
            
            addOptions(categories);
        });
    
    document.getElementById('moveCategoryModal').classList.remove('hidden');
    document.getElementById('moveCategoryModal').classList.add('flex');
}

// 隐藏移动分类模态框
function hideMoveModal() {
    document.getElementById('moveCategoryModal').classList.add('hidden');
    document.getElementById('moveCategoryModal').classList.remove('flex');
}

// 移动分类
function moveCategory() {
    const form = document.getElementById('moveCategoryForm');
    const formData = new FormData(form);
    
    fetch(`{{ admin_url }}/categories/${form.category_id.value}/move`, {
        method: 'POST',
        headers: {
            'X-CSRFToken': '{{ csrf_token() }}'
        },
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            showAlert(data.error, 'error', '错误');
        } else {
            showAlert(data.message, 'success', '成功');
            setTimeout(() => location.reload(), 500);
        }
    });
}

// 删除分类
function deleteCategory(categoryId) {
    showAlert('确定要删除此分类吗？分下的文章将移动到默认分类！', 'warning', '确认删除', function() {
        fetch(`{{ admin_url }}/categories/${categoryId}`, {
            method: 'DELETE',
            headers: {
                'X-CSRFToken': '{{ csrf_token() }}'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                showAlert(data.error, 'error', '错误');
            } else {
                showAlert(data.message, 'success', '成功');
                setTimeout(() => location.reload(), 1000);
            }
        });
    });
}

// 初始化拖拽排序
new Sortable(document.getElementById('categoryList'), {
    handle: '.category-item',
    animation: 150,
    onEnd: function(evt) {
        const categoryIds = Array.from(evt.to.children).map(el => el.dataset.id);
        fetch('{{ admin_url }}/categories/sort', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': '{{ csrf_token() }}'
            },
            body: JSON.stringify({ category_ids: categoryIds })
        })
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                showAlert(data.error, 'error', '错误');
                location.reload();
            } else {
                showAlert('排序已更新', 'success', '成功');
            }
        });
    }
});

// 显示批量设置模态框
function showBatchPerPageModal() {
    document.getElementById('batchPerPageModal').classList.remove('hidden');
    document.getElementById('batchPerPageModal').classList.add('flex');
}

// 隐藏批量设置模态框
function hideBatchPerPageModal() {
    document.getElementById('batchPerPageModal').classList.add('hidden');
    document.getElementById('batchPerPageModal').classList.remove('flex');
    document.getElementById('batchPerPageForm').reset();
}

// 保存批量设置
function saveBatchPerPage() {
    const form = document.getElementById('batchPerPageForm');
    const perPage = form.per_page.value;
    
    if (!perPage || perPage < 1 || perPage > 100) {
        showAlert('请输入1-100之间的数值', 'error', '错误');
        return;
    }
    
    fetch('{{ admin_url }}/categories/batch-per-page', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': '{{ csrf_token() }}'
        },
        body: JSON.stringify({ per_page: parseInt(perPage) })
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            showAlert(data.error, 'error', '错误');
        } else {
            showAlert(data.message, 'success', '成功');
            setTimeout(() => location.reload(), 500);
        }
        hideBatchPerPageModal();
    });
}

// 页面加载完成后自动更新分类计数
document.addEventListener('DOMContentLoaded', function() {
    // 获取当前页面所有分类ID
    const categoryElements = document.querySelectorAll('[data-category-id]');

    const categoryIds = Array.from(categoryElements).map(el => parseInt(el.dataset.categoryId));

    if (categoryIds.length > 0) {
        // 调用更新API
        fetch('{{ admin_url }}/categories/update-counts', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': '{{ csrf_token() }}'
            },
            body: JSON.stringify({ category_ids: categoryIds })
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('请求失败');
            }
            return response.json();
        })
        .then(data => {
            console.log('更新分类数据:', data);
            if (data.error) {
                console.error('更新分类数据失败:', data.error);
                return;
            }
            if (data.success && data.updated.length > 0) {
                // 更新页面显示
                data.updated.forEach(item => {
                    const countEl = document.querySelector(`[data-category-id="${item.id}"] .article-count`);
                    if (countEl) {
                        console.log(`更新分类 ${item.id} 的计数为 ${item.new_count}`);
                        countEl.textContent = item.new_count;
                        // 添加更新动画效果
                        countEl.classList.add('text-green-600', 'animate-pulse');
                        setTimeout(() => {
                            countEl.classList.remove('text-green-600', 'animate-pulse');
                        }, 2000);
                    }
                });
            }
        })
        .catch(error => {
            console.error('更新分类计数失败:', error);
        });
    } else {
        console.log('没有找到分类元素'); // 调试信息
    }
});

// 添加更新所有分类计数的函数
function updateAllCategoryCounts() {
    showAlert(
        '此操作会重新计算所有分类的文章数，在分类计数不准确时使用。确定要继续吗？', 
        'warning', 
        '更新所有分类计数', 
        function() {
            // 显示加载提示
            showAlert('正在更新所有分类计数...', 'info', null, null, false);
            
            fetch('{{ admin_url }}/categories/update-all-counts', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': '{{ csrf_token() }}'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    showAlert(data.error, 'error', '错误');
                    return;
                }
                if (data.success) {
                    showAlert('所有分类计数已更新', 'success', '成功');
                    setTimeout(() => location.reload(), 200);
                }
            })
            .catch(error => {
                showAlert('更新失败: ' + error, 'error', '错误');
            });
        },
        true  // 显示取消按钮
    );
}
</script>

<!-- 在页面底部添加样式 -->
<style>
.custom-scrollbar::-webkit-scrollbar {
    width: 6px;
}

.custom-scrollbar::-webkit-scrollbar-track {
    background: transparent;
}

.custom-scrollbar::-webkit-scrollbar-thumb {
    background-color: rgba(156, 163, 175, 0.5);
    border-radius: 3px;
}

.custom-scrollbar::-webkit-scrollbar-thumb:hover {
    background-color: rgba(156, 163, 175, 0.8);
}

/* 暗色模式 */
.dark .custom-scrollbar::-webkit-scrollbar-thumb {
    background-color: rgba(156, 163, 175, 0.3);
}

.dark .custom-scrollbar::-webkit-scrollbar-thumb:hover {
    background-color: rgba(156, 163, 175, 0.5);
}
</style>
{% endblock %} 